<template>
  <div class="container">
    <!--面包屑导航-->
    <Breadcrumb :items="['menu.system', '用户管理']" />
    <div style="display: flex;flex-direction: row;">
      <!--部门树-->
      <a-card
        class="general-card"
        style="margin-right: 10px;"
      >
        <a-tree
          v-if="deptList.length > 0"
          v-model:selected-keys="deptId"
          :field-names="fieldNames"
          :data="deptList"
          show-line
          @select="fetchData"
        >
          <template #icon>
            <icon-folder />
          </template>
        </a-tree>
      </a-card>
      <!--表格空间-->
      <div style="flex:1">
        <query-header
          :config="queryConfig"
          @search="search"
          @reset="reset"
        />
        <a-card class="general-card">
          <header-operator
            :operators="headerOperators"
            :columns="tableColumns"
            @operator="operator"
            @refresh="fetchData"
            @density="(value) => {size = value}"
            @column="(value) => cloneColumns = value"
          />
          <!--列表-->
          <a-table
            row-key="userId"
            :size="size"
            :bordered="{cell:true}"
            :loading="loading"
            :columns="cloneColumns"
            :data="tableData"
            :pagination="pagination"
            @page-change="pageChange"
            @page-size-change="pageSizeChange"
          >

            <template #sex="{ record }">
              <a-tag v-if="record.sex=== '1'" color="magenta">女</a-tag>
              <a-tag v-else-if="record.sex=== '0'" color="arcoblue">男</a-tag>
              <a-tag v-else color="gray">未知</a-tag>
            </template>

            <template #userType="{ record }">
              <a-tag v-if="record.userType=== '1'" color="arcoblue">系统用户</a-tag>
              <a-tag v-if="record.userType=== '0'" color="gray">注册用户</a-tag>
            </template>

            <template #status="{ record }">
              <a-tag v-if="record.status=== '1'" color="gray">冻结</a-tag>
              <a-tag v-if="record.status=== '0'" color="arcoblue">正常</a-tag>
            </template>

            <template #operations="{ record }">
              <column-operator
                :btn-size="size"
                :config="columnOperators"
                :record="record"
                @record-operator="recordOperator"
              />
            </template>
          </a-table>
        </a-card>

        <!-- 新增用户对话框 -->
        <dialog-add ref="dialogAddRef" @submit="fetchData" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { userList, deleteUser, resetPassword, SysUser } from '@/api/system/user';
import { deptTree } from '@/api/system/dept';
import cloneDeep from 'lodash/cloneDeep';
import useLoading from '@/hooks/loading';
import { Message, Modal, PaginationProps } from '@arco-design/web-vue';
import { headerOperators, tableColumns, columnOperators } from '@/views/system/user/config';
import QueryHeader from '@/views/system/user/query-header.vue';
import DialogAdd from '@/views/system/user/dialog/dialog-add.vue';

const { loading, setLoading } = useLoading(true);

const deptList = ref([]);

const deptId = ref([]);

const queryParams = ref();

const size = ref('medium');

const tableData = ref<SysUser[]>([]);

const cloneColumns = ref<any>([]);

const fieldNames = ref({
  key: 'deptId',
  title: 'deptName',
  children: 'children'
});

const basePagination: PaginationProps = {
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true
};

const pagination = reactive({
  ...basePagination
});

const pageChange = (page: number | undefined) => {
  pagination.current = page;
  fetchData();
};

const pageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  fetchData();
};

const fetchData = async () => {
  setLoading(true);
  try {
    const params = {
      page: {
        current: pagination.current,
        size: pagination.pageSize
      },
      query: {
        ...queryParams.value,
        'deptId': deptId.value.length ? deptId.value[0] : ''
      }
    };
    const { data } = await userList(params);
    tableData.value = data.records;
    pagination.current = Number(data.current);
    pagination.total = Number(data.total);
  } finally {
    setLoading(false);
  }
};

const search = (value: SysUser) => {
  queryParams.value = value;
  fetchData();
};

const reset = () => {
  queryParams.value = {};
  deptId.value = [];
  fetchData();
};

const dialogAddRef = ref();

const operator = (value: string) => {
  if (value === 'add') {
    dialogAddRef.value.open(null, false);
  }
};

const recordOperator = (value: string, record: SysUser, setLoading: any) => {
  if (value === 'detail') {
    dialogAddRef.value.open(record, true);
    return;
  }
  if (value === 'update') {
    dialogAddRef.value.open(record, false);
    return;
  }
  if (value === 'delete') {
    const userId = record.userId || '';
    Modal.warning({
      content: `确定删除用户【${record.userName}】`,
      simple: true,
      hideCancel: false,
      cancelText: '取消',
      onOk: () => {
        deleteUser(userId).then(() => {
          Message.info('删除成功');
          fetchData();
        });
      }
    });
    return;
  }
  if (value === 'reset') {
    const userId = record.userId || '';
    Modal.warning({
      content: `确定重置【${record.userName}】用户的密码`,
      simple: true,
      hideCancel: false,
      cancelText: '取消',
      onOk: () => {
        resetPassword(userId).then(() => {
          Message.info('重置密码成功');
          fetchData();
        });
      }
    });
  }
};

onMounted(() => {
  fetchData();
  deptTree(false).then(({ data }) => {
    deptList.value = data;
  });
});

watch(
  () => tableColumns.value,
  (val) => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item: { checked: boolean; }, index: any) => {
      item.checked = true;
    });
  },
  { deep: true, immediate: true }
);
</script>

<script lang="ts">
export default {
  name: 'SysUser'
};
</script>

<style scoped lang="less">
@import "/src/components/table/common";
</style>
